package com.xht.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xht.constants.SystemConstants;
import com.xht.domain.ResponseResult;
import com.xht.domain.dto.CategoryChangeStatusDto;
import com.xht.domain.dto.CategoryDto;
import com.xht.domain.entity.Article;
import com.xht.domain.entity.Category;
import com.xht.enums.AppHttpCodeEnum;
import com.xht.exception.SystemExceptin;
import com.xht.mapper.CategoryMapper;
import com.xht.service.ArticleService;
import com.xht.service.CategoryService;
import com.xht.utils.BeanCopyUtils;
import com.xht.vo.CategoryVo;
import com.xht.vo.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
 * 分类表(Category)表服务实现类
 *
 * @author makejava
 * @since 2025-02-21 11:53:03
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private ArticleService articleService;

    @Override
    public ResponseResult getCategoryList() {
        //1、查询文章表状态为已发布
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        List<Article> ArticleList = articleService.list(queryWrapper);
        //2、查询文章表中已发布文章的 分类ID并去重
        Set<Long> CategoryIds = ArticleList.stream()
                .map(new Function<Article, Long>() {
                    @Override
                    public Long apply(Article article) {
                        return article.getCategoryId();
                    }
                }).collect(Collectors.toSet());
        //3、查询分类表
        List<Category> categories = listByIds(CategoryIds);

        List<Category> collect = categories.stream()
                .filter(category -> SystemConstants.STATUS_NORMAL.equals(category.getStatus()))
                .collect(Collectors.toList());

        //4、封装VO
        List<CategoryVo> categoryVos = BeanCopyUtils.copyBeanList(collect, CategoryVo.class);


        return ResponseResult.okResult(categoryVos);
    }

    /**
     * 后台管理-写博客模块-展示可供选择的所有文章分类
     *
     * @return
     */
    @Override
    public ResponseResult listAllCategory() {

        List<Category> list = list();
        List<CategoryVo> categoryVos = BeanCopyUtils.copyBeanList(list, CategoryVo.class);
        return ResponseResult.okResult(categoryVos);
    }

    /**
     * 分类模块 -- 显示分类列表
     *
     * @param pageNum
     * @param pageSize
     * @param name
     * @param status
     * @return
     */
    @Override
    public ResponseResult categoryList(Integer pageNum, Integer pageSize, String name, String status) {
        //模糊查询
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(name), Category::getName, name)
                .eq(StringUtils.hasText(status), Category::getStatus, status);
        //分类查询
        Page<Category> page = new Page<>(pageNum, pageSize);
        page(page, queryWrapper);

        //封转数据
        List<Category> records = page.getRecords();
        List<CategoryVo> categoryVos = BeanCopyUtils.copyBeanList(records, CategoryVo.class);

        PageVo pageVo = new PageVo(categoryVos, page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    /**
     * 新增 分类
     *
     * @param categoryDto
     * @return
     */
    @Override
    public ResponseResult addCategory(CategoryDto categoryDto) {
        Category category = BeanCopyUtils.copyBean(categoryDto, Category.class);
        save(category);
        return ResponseResult.okResult();
    }

    /**
     * 编辑分类--回显 所选的分类信息
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult getCategoryById(Integer id) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getId, id);
        Category category = baseMapper.selectOne(queryWrapper);

        return ResponseResult.okResult(category);
    }

    /**
     * 更新 分类
     *
     * @param category
     * @return
     */
    @Override
    public ResponseResult updateCategory(Category category) {

        updateById(category);
        return ResponseResult.okResult();
    }

    /**
     * 删除分类
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteCategory(Integer id) {
        //如果文章表 中 无该分类的 文章,那即可删除
        if (!this.StopCategory(id)) {
            throw new SystemExceptin(AppHttpCodeEnum.NOT_DELETE_CATEGORY);
        }
//        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Article::getCategoryId, id);
//        Integer count = articleService.getBaseMapper().selectCount(queryWrapper);
//        if (count != 0) {
//            throw new SystemExceptin(AppHttpCodeEnum.NOT_DELETE_CATEGORY);
//        }

        LambdaUpdateWrapper<Category> updateWrapper = Wrappers.lambdaUpdate(Category.class)
                .eq(Category::getId, id)
                .set(Category::getDelFlag, SystemConstants.CATEGORY_DELETE);
        update(updateWrapper);
        return ResponseResult.okResult();
    }

    /**
     * 更改 分类 状态
     *
     * @param categoryChangeStatusDto
     * @return
     */
    @Override
    public ResponseResult changeStatus(CategoryChangeStatusDto categoryChangeStatusDto) {
        Long categoryId = categoryChangeStatusDto.getCategoryId();
        String status = categoryChangeStatusDto.getStatus();
        //如果是要停用 该分类 需要判断是否可以 停用
        if (status.equals(SystemConstants.CATEGORY_STATUS_DRAFT)) {
            if (!this.StopCategory(categoryId.intValue())) {
                throw new SystemExceptin(AppHttpCodeEnum.NOT_DELETE_CATEGORY);
            }
        }

        LambdaUpdateWrapper<Category> updateWrapper = Wrappers.lambdaUpdate(Category.class).eq(Category::getId, categoryId)
                .set(Category::getStatus, status);
        update(updateWrapper);
        return ResponseResult.okResult();
    }

    /**
     * 判断 可不可以 停用 该分类
     *
     * @param categoId
     * @return
     */
    public boolean StopCategory(Integer categoId) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getCategoryId, categoId);
        Integer count = articleService.getBaseMapper().selectCount(queryWrapper);
        return count == 0;
    }
}

